package com.xes.attend.rd60n.utils;

public class StringUtils {
	
	/**
	 * 统计字符串的真实长度，汉字占2个，英文字符占1个
	 * @param str 字符串
	 * @return 字符串真实长度
	 */
	public static int trueLength(String str)
	{
		int str_len = 0;
		String chinese = "[\u4e00-\u9fa5]";
		
		if (str == null) {
			return 0;
		}
		
		for (int i = 0; i < str.length(); i++) {
			String tmp = str.substring(i, i+1);
			if (tmp.matches(chinese)) {
				str_len += 2;
			} else {
				str_len += 1;
			}
		}
		
		return str_len;
	}
	
	public static String fixSubString(String str, int len)
	{
		int i = 0;
		int str_len = 0;
		String chinese = "[\u4e00-\u9fa5]";
		StringBuilder stringBuilder = new StringBuilder("");

		for (i = 0; i < str.length(); i++) {
			String tmp = str.substring(i, i+1);
			if (tmp.matches(chinese)) {
				str_len += 2;
			} else {
				str_len += 1;
			}
			if (str_len > len) {
				break;
			}
			stringBuilder.append(tmp);
		}
		
		for (; str_len < len; str_len+=2) {
			stringBuilder.insert(0, " ");
			if (str_len + 1 >= len) {
				break;
			}
			stringBuilder.append(" ");
		}
		
		return stringBuilder.toString();
	}
	
}
